package com.tianqingwl.gsystem.resources.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianqingwl.gsystem.common.vo.CommonResultVo;
import com.tianqingwl.gsystem.common.vo.PageResultVo;
import com.tianqingwl.gsystem.resources.pojo.SysConfig;
import com.tianqingwl.gsystem.resources.service.SysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@RequestMapping("/manage/config")
@Controller
@PreAuthorize("@gs.check('sys_manage_config')")
public class SysConfigController {

    @Autowired
    private SysConfigService sysConfigService;

    @GetMapping("/config-manage.html")
    public String configManagePage(Model model){
        //查询配置组
        List<String> configGroupList = sysConfigService.listAllConfigGroup();
        model.addAttribute("configGroupList",configGroupList);
        return "manage/config/config-manage";
    }

    @GetMapping("/config-edit.html")
    public String configEditPage(Model model,Long configId){
        if (configId!=null){
            SysConfig sysConfig = sysConfigService.getSysConfig(configId);
            model.addAttribute("sysConfig",sysConfig);
        }
        return "manage/config/config-edit";
    }

    @GetMapping("/list")
    @ResponseBody
    public Object list(Integer searchType,String searchStr,Long page,Long limit,String configGroup){
        page = page==null?1:page;
        limit = limit==null?10:limit;
        Page<SysConfig> sysConfigPage = new Page<>(page,limit);

        sysConfigService.list(sysConfigPage,searchType,searchStr,configGroup);
        return PageResultVo.success(sysConfigPage.getTotal(),sysConfigPage.getPages(),sysConfigPage.getRecords());
    }

    @PostMapping("/configSave")
    @ResponseBody
    public Object configSave(SysConfig sysConfig){
        try{
            sysConfigService.save(sysConfig);
            return CommonResultVo.success(sysConfig);
        }catch (Exception e){
            e.printStackTrace();
            return CommonResultVo.fail(e.getMessage());
        }
    }
}
